/* Copyright (c) 2010, mitsuhisa.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the misuhisa.net nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdexcept>
#include "Context.hpp"
#include "String.hpp"
#include "Native.hpp"
#include "BuiltinPrototype.hpp"
#include "Parser.hpp"
#include "Tree.hpp"

namespace nyu {

namespace {

int init_count = 0;

}

Context::Context() :
        current_scope_(new Scope()), is_updated_(false), scope_cache_idx_(0),
        current_target_(0) {
    if (!init_count++) {
        StrPool::initialize();
        Symtbl::initialize();
        String::initialize();
        BuiltinPrototype::initialize();
    }

    // add builtin objects
    putSymref(Symtbl::getIndex(String::OBJECT), BuiltinPrototype::OBJECT);
    putSymref(Symtbl::getIndex(String::STRING), BuiltinPrototype::STRING);
    putSymref(Symtbl::getIndex(String::ARRAY), BuiltinPrototype::ARRAY);
    putSymref(Symtbl::getIndex(String::RANGE), BuiltinPrototype::RANGE);
}

Context::~Context() {
    popScope();

    for (int i = 0, j = scope_cache_idx_; i < j; i++) {
        delete scope_cache_[i];
    }

    if (is_object(current_target_) && !is_null(current_target_))
        value_to_object(current_target_)->unref();

    if (!--init_count) {
        BuiltinPrototype::finalize();
        String::finalize();
        StrPool::finalize();
        Symtbl::finalize();
    }
}

void Context::putFunction(const char* name, func_type func) {
    String* str = StrPool::get(::strdup(name));
    unsigned int i = Symtbl::getIndex(str);
    str->unref();
    putSymref(i, object_to_value(new Native(func)));
}

Value Context::evalFile(const char* filename) {
    FILE* fp = ::fopen(filename, "r");
    if (!fp) {
        throw std::runtime_error("cannot open file");
    }

    parser::Parser parser;
    parser.setSource(fp);

    try {
        if (parser.parse() != 0) {
            throw std::runtime_error("parse failed");
        }
    } catch (std::exception& e) {
        ::fclose(fp);
        return NULL_VALUE;
    }

    ::fclose(fp);

    parser::Tree* t = parser.result();

    Value ret = NULL_VALUE;
    try {
        ret = t->eval(*this);
    } catch (std::exception& e) {
        delete t;
        throw;
    }

    delete t;

    return ret;
}

Value Context::evalString(const char* script) {
    parser::Parser parser;
    parser.setSource(script);

    try {
        if (parser.parse() != 0) {
            throw std::runtime_error("parse failed");
        }
    } catch (std::exception& e) {
        return NULL_VALUE;
    }

    parser::Tree* t = parser.result();

    Value ret = NULL_VALUE;
    try {
        ret = t->eval(*this);
    } catch (std::exception& e) {
        delete t;
        throw;
    }

    delete t;

    return ret;
}

}
